<template>
  <div :class="['tui-chat', !isPC && 'tui-chat-h5']">
    <div
      v-if="currentConversationID"
      :class="['tui-chat', !isPC && 'tui-chat-h5']"
    >
      <ChatHeader
        :class="[
          'tui-chat-header',
          !isPC && 'tui-chat-H5-header',
          isUniFrameWork && 'tui-chat-uniapp-header',
        ]"
        :canCloseChat="props.canCloseChat"
        @closeChat="closeChat"
      />
      <MessageList
        ref="messageListRef"
        :class="['tui-chat-message-list', !isPC && 'tui-chat-h5-message-list']"
        @handleEditor="handleEditor"
        @closeInputToolBar="() => changeToolbarDisplayType('none')"
      />
      <MessageInputToolbar
        v-if="isInputToolbarShow"
        :class="[
          'tui-chat-message-input-toolbar',
          !isPC && 'tui-chat-h5-message-input-toolbar',
          isUniFrameWork && 'tui-chat-uni-message-input-toolbar',
        ]"
        :displayType="inputToolbarDisplayType"
        @insertEmoji="insertEmoji"
        @changeToolbarDisplayType="changeToolbarDisplayType"
        @scrollToLatestMessage="scrollToLatestMessage"
      />
      <MessageInput
        ref="messageInputRef"
        :class="[
          'tui-chat-message-input',
          !isPC && 'tui-chat-h5-message-input',
          isUniFrameWork && 'tui-chat-uni-message-input',
          isWeChat && 'tui-chat-wx-message-input',
        ]"
        :isMuted="false"
        :muteText="TUITranslateService.t('TUIChat.您已被管理员禁言')"
        :placeholder="TUITranslateService.t('TUIChat.请输入消息')"
        :inputToolbarDisplayType="inputToolbarDisplayType"
        @changeToolbarDisplayType="changeToolbarDisplayType"
        @emojiShow="emojiShow"
        @toolShow="toolShow"
        @blurToolAndEmojiH5="blurToolAndEmojiH5"
      />
      <div class="input-toolbar-h5">
        <div :class="['emoji-dialog-h5',(toolShowH5 && !emojiOpen)?'tool-dialog-h5':'']">
          <div v-if="emojiOpen">
            <EmojiDialog
              @insertEmoji="insertEmoji"
               @sendMessage="sendMessage"
            />
          </div>
          <MessageInputToolbar
            v-if="!isPC"
            :class="[
              'tui-chat-message-input-toolbar',
              !isPC && 'tui-chat-h5-message-input-toolbar',
              isUniFrameWork && 'tui-chat-uni-message-input-toolbar',
            ]"
            :isH5ToolShow="toolShowH5"
            :displayType="inputToolbarDisplayType"
            @insertEmoji="insertEmoji"
            @changeToolbarDisplayType="changeToolbarDisplayType"
            @scrollToLatestMessage="scrollToLatestMessage"
            @sendMessage="sendMessage"
          />
        </div>
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
import vue from '../../adapter-vue';
import {
  TUITranslateService,
  TUIConversationService,
  TUIStore,
  StoreName,
  IMessageModel,
  TUIChatEngine
} from '@tencentcloud/chat-uikit-engine';
import TUICore, { TUIConstants, TUILogin } from '@tencentcloud/tui-core';
import ChatHeader from './chat-header/index-web.vue';
import MessageList from './message-list/index-web.vue';
import MessageInput from './message-input/index-web.vue';
import MessageInputToolbar from './message-input-toolbar/index-web.vue';
import EmojiDialog from './message-input-toolbar/emoji-dialog-mobile/emoji-dialog-mobile.vue';
import { isPC, isH5 ,isWeChat, isUniFrameWork } from '../../utils/env';
import { ToolbarDisplayType } from '../../interface';
import logger from '../../logger/index';
const { ref, onMounted, onUnmounted, computed } = vue;

interface IProps {
  canCloseChat?: boolean;
  sdkAPPID?:number;
  userID?:string;
  userSig?:string;
}

const emits = defineEmits(['closeChat']);

const currentConversationID = ref();
const inputToolbarDisplayType = ref<ToolbarDisplayType>('none');
const messageInputRef = ref();
const messageListRef = ref<InstanceType<typeof MessageList>>();
const emojiOpen = ref(false);
const toolShowH5 = ref(false);
const props = withDefaults(defineProps<IProps>(), {
  canCloseChat: true,
  sdkAPPID: 0,
  userID: '',
  userSig: '',
});

const loginCustomerUIKit = () => {
  TUILogin.login({
    SDKAppID: props.sdkAPPID as number,
    userID: props.userID,
    userSig: props.userSig,
    useUploadPlugin: true,
  }).then(() => {
    console.log("login success");
  })
  .catch((error) => {
    console.log(error);
  })
  const { chat, SDKAppID, userID, userSig } = TUILogin.getContext();
    TUIChatEngine.login({
      chat,
      SDKAppID,
      userID,
      userSig,
    });
    currentConversationID.value = 'C2C@@customer_service_account';
    TUIStore.update(StoreName.CONV, 'currentConversationID','C2C@customer_service_account');
}

try {
  const userContext = TUILogin.getContext();
  if(props.sdkAPPID!==0 && props.userID!=='' && props.userSig!==''){
    loginCustomerUIKit();
  }
  logger.info({
    msg: 'customer serivce plugin init',
    attributes: {
      SDKAppID: userContext?.SDKAppID,
      userID: userContext?.userID,
      userAgent: navigator?.userAgent?.toLowerCase(),
      source: 'web-vue',
      pluginVersion: '2.2.7',
    },
  });
} catch (e) {
  logger.info('logger fail');
}

onMounted(() => {
  TUIStore.watch(StoreName.CONV, {
    currentConversationID: onCurrentConversationIDUpdate,
  });
});

onUnmounted(() => {
  TUIStore.unwatch(StoreName.CONV, {
    currentConversationID: onCurrentConversationIDUpdate,
  });
});

const isInputToolbarShow = computed<boolean>(() => {
  return (isUniFrameWork || isH5) ? inputToolbarDisplayType.value !== 'none' : true;
});

const reset = () => {
  TUIConversationService.switchConversation('');
};

const closeChat = (conversationID: string) => {
  emits('closeChat', conversationID);
  reset();
};

const insertEmoji = (emojiObj: object) => {
  messageInputRef.value?.insertEmoji(emojiObj);
};
const sendMessage = () => {
  messageInputRef.value?.sendMessage();
}

const handleEditor = (message: IMessageModel, type: string) => {
  if (!message || !type) return;
  switch (type) {
    case 'reference':
      // todo
      break;
    case 'reply':
      // todo
      break;
    case 'reedit':
      if (message?.payload?.text) {
        messageInputRef?.value?.reEdit(message?.payload?.text);
      }
      break;
    default:
      break;
  }
};

function changeToolbarDisplayType(type: ToolbarDisplayType) {
  inputToolbarDisplayType.value
    = inputToolbarDisplayType.value === type ? 'none' : type;
  if (inputToolbarDisplayType.value !== 'none' && isUniFrameWork) {
    uni.$emit('scroll-to-bottom');
  }
}

function scrollToLatestMessage() {
  messageListRef.value?.scrollToLatestMessage();
}

function onCurrentConversationIDUpdate(conversationID: string) {
  if (currentConversationID.value === conversationID) {
    return;
  }

  currentConversationID.value = conversationID;

  // The TUICustomerServicePlugin plugin determines if the current conversation is a customer service conversation, then sets chatType and activates the conversation.
  TUICore.callService({
    serviceName: TUIConstants.TUICustomerServicePlugin.SERVICE.NAME,
    method:
      TUIConstants.TUICustomerServicePlugin.SERVICE.METHOD.ACTIVE_CONVERSATION,
    params: { conversationID: conversationID },
  });
}

function emojiShow(){
  if(toolShowH5.value === true){
    toolShowH5.value = false;
  }
  emojiOpen.value = !emojiOpen.value;
  
}

function toolShow(){
  if(emojiOpen.value === true){
    emojiOpen.value = false;
  }
  toolShowH5.value = !toolShowH5.value;
}

function blurToolAndEmojiH5(){
  if(emojiOpen.value === true){
    emojiOpen.value = false;
  }
  toolShowH5.value = false;
  
}
</script>

<style scoped lang="scss" src="./style/index.scss">

</style>
